package top.kaoshanji.p2ch10b;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.u1constant.FileConstant;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 代码清单-p2ch10b-324页a：写入Java对象的内容到文件中
 * author kaoshanji
 * ^_^
 * create time 2025/2/3 10:14
 */
public class WriteUser {

    private static final Logger logger = LogManager.getLogger(WriteUser.class);

    public static void main(String[] args) {
        logger.info("...代码清单-p2ch10b-324页a：写入Java对象的内容到文件中...");

        WriteUser writeUser = new WriteUser();
        User user = new User("Alex", "alex@example.org");
        writeUser.write(user);

    }

    public void write(User user) {

        Path path = Paths.get(FileConstant.LOCAL_ROOT_PATH.concat("p2ch10b324页a\\user.bin"));
        try (ObjectOutputStream output = new ObjectOutputStream(Files.newOutputStream(path))) {
            output.writeObject(user);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}
